package main

import (
	"encoding/json"
	"html/template"
	"net/http"

	"github.com/unrolled/render"
)

// IndexHandler  去首页
func IndexHandler(w http.ResponseWriter, r *http.Request) {
	//解析模板
	t := template.Must(template.ParseFiles("source/views/index.html"))
	//执行
	t.Execute(w, "Outlander")
}

func AccessHandler(w http.ResponseWriter, r *http.Request) {
	//解析模板
	t := template.Must(template.ParseFiles("source/views/jsaccess.html"))
	//执行
	t.Execute(w, "www.baidu.com")
}

func FormContentHandler(w http.ResponseWriter, r *http.Request) {
	t := template.Must(template.ParseFiles("source/views/content.html"))
	r.ParseForm()

	t.Execute(w, r.Form)
}

func NotImplemented() []byte {
	return []byte("501 Not Implemented")
}

func NotImplementedHandler(w http.ResponseWriter, r *http.Request) {
	w.Write(NotImplemented())
}

func ApiTest2Handler(w http.ResponseWriter, req *http.Request) {

	formatter := render.New()
	formatter.JSON(w, http.StatusOK, struct {
		ID      string `json:"id"`
		Content string `json:"content"`
	}{ID: "8675309", Content: "Hello from Go!"})
}

func ApiTestHandler(w http.ResponseWriter, r *http.Request) {
	data, _ := json.Marshal(struct {
		ID      string
		Content string
	}{ID: "Hello", Content: "Hello world"})

	w.Write(data)
}

func ApiDataHandler(w http.ResponseWriter, r *http.Request) {

	data := struct {
		Apple  int
		Huawei int
		Oppo   int
		Ov     int
		Xiaomi int
	}{
		Apple:  20,
		Huawei: 20,
		Oppo:   20,
		Ov:     20,
		Xiaomi: 20,
	}

	render.New().JSON(w, http.StatusOK, data)

}

func main() {
	//设置处理静态资源
	http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.Dir("static/"))))
	http.HandleFunc("/", IndexHandler)
	http.HandleFunc("/api/unknown", NotImplementedHandler)
	http.HandleFunc("/api/test", ApiTestHandler)
	http.HandleFunc("/api/test2", ApiTest2Handler)
	http.HandleFunc("/api/data", ApiDataHandler)
	http.HandleFunc("/formpost", FormContentHandler)
	http.HandleFunc("/jsaccess", AccessHandler)
	http.ListenAndServe(":8080", nil)
}
